package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusLinearLayout;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BrandInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.PriceConditionInfo;
import com.chexiehui.jc.event.ChooseBrandEvent;
import com.chexiehui.jc.mvp.car.CarGarageAssistantCovenant;
import com.chexiehui.jc.mvp.car.CarGarageAssistantPresenter;
import com.chexiehui.jc.ui.activity.CarGarageAssistantDetailsActivity;
import com.chexiehui.jc.ui.activity.ChooseCarModelActivity;
import com.chexiehui.jc.ui.activity.SearchActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.CustomAssistantMorePopup;
import com.chexiehui.jc.widget.CustomChooseBrandPopup;
import com.chexiehui.jc.widget.CustomChoosePricePopup;
import com.chexiehui.jc.widget.LoadingLayout;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 二手车
 */

public class CarGarageAssistantFragment extends BaseMvpLazyLoadFragment<CarGarageAssistantPresenter> implements
        CarGarageAssistantCovenant.View, CustomChooseBrandPopup.ICustomChooseBrandPopupListener,
        CustomChoosePricePopup.ICustomChoosePricePopupListener, CustomAssistantMorePopup.ICustomAssistantMoreListener {

    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.ll_head_search)
    RadiusLinearLayout llHeadSearch;
    @BindView(R.id.tv_choose_brand)
    TextView tvChooseBrand;
    @BindView(R.id.rl_choose_brand)
    RelativeLayout rlChooseBrand;
    @BindView(R.id.tv_choose_price)
    TextView tvChoosePrice;
    @BindView(R.id.rl_choose_price)
    RelativeLayout rlChoosePrice;
    @BindView(R.id.rl_choose_more)
    RelativeLayout rlChooseMore;
    @BindView(R.id.ll_choose_panel)
    LinearLayout llChoosePanel;

    private List<CarInfo> listData;
    private CommonAdapter<CarInfo> listAdapter;
    private BasePage<CarInfo> page;
    private CustomChooseBrandPopup customChooseBrandPopup;
    private CustomChoosePricePopup customChoosePricePopup;
    private CustomAssistantMorePopup customAssistantMorePopup;
    private BrandInfo chooseBrand;
    private PriceConditionInfo choosePrice;
    private DictInfo chooseGrade;
    private DictInfo chooseCountry;
    private List<DictInfo> gradeList;
    private List<DictInfo> countryList;
    private String cityName = "";

    public static CarGarageAssistantFragment getInstance() {
        CarGarageAssistantFragment fragment = new CarGarageAssistantFragment();
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_garage_assistant;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        refreshLayout.setDragRate(0.5f);
        loadingLayout.setStatus(LoadingLayout.Loading);
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh();
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listAdapter.getDatas().size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        mRecycler.setLayoutManager(new LinearLayoutManager(mActivity));
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<CarInfo>(mActivity, R.layout.item_car_garage_assistant, listData) {
            @Override
            protected void convert(ViewHolder holder, CarInfo item, int position) {
                GlideUtil.loadImageViewCrop(mActivity, item.getImg(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getBrandName() + " " + item.getSeriesName() + " " + item.getName());
                holder.setText(R.id.tv_item_area, item.getCity());
                holder.setText(R.id.tv_item_year, item.getRegistrationYearStr());
                holder.setText(R.id.tv_item_mileage, item.getDrivingDistanceStr());
                holder.setText(R.id.tv_item_price, item.getPriceUnit());
                holder.setText(R.id.tv_item_agent_price, item.getAgentPriceStr());
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarGarageAssistantDetailsActivity.class,
                        new BundleBuilder().putString("carId", listData.get(position).getId()).create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRecycler.setAdapter(listAdapter);
        mvpPresenter.getCountryTypeList();
        mvpPresenter.getCraGradeList();
        isPrepared = true;
        lazyLoad();
    }

    @OnClick({R.id.ll_head_search, R.id.rl_choose_brand, R.id.rl_choose_price, R.id.rl_choose_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_head_search:
                startActivity(SearchActivity.class);
                break;
            case R.id.rl_choose_brand:
                showChooseBrandPopup();
                break;
            case R.id.rl_choose_price:
                showChoosePricePopup();
                break;
            case R.id.rl_choose_more:
                showChooseMore();
                break;
        }
    }

    @Override
    public void onAssistantMoreChooseBrand() {
        startActivity(ChooseCarModelActivity.class, new BundleBuilder()
                .putInt("chooseLevel", 1)
                .putInt("eventTag", 300)
                .create());
    }

    @Override
    public void onAssistantMoreSure(BrandInfo chooseBrand, PriceConditionInfo choosePrice, DictInfo chooseGrade, DictInfo chooseCountry) {
        this.chooseBrand = chooseBrand;
        this.choosePrice = choosePrice;
        this.chooseGrade = chooseGrade;
        this.chooseCountry = chooseCountry;
        if (chooseBrand != null) {
            tvChooseBrand.setText(chooseBrand.getName());
        } else {
            tvChooseBrand.setText("品牌");
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    private void showChooseMore() {
        if (customAssistantMorePopup == null) {
            customAssistantMorePopup = new CustomAssistantMorePopup(mActivity);
            customAssistantMorePopup.setListener(this);
        }
        customAssistantMorePopup.initModel(chooseBrand, choosePrice, chooseGrade, chooseCountry, gradeList, countryList);
        new XPopup.Builder(getContext())
                .hasStatusBarShadow(false)
                .asCustom(customAssistantMorePopup)
                .show();
    }

    @Override
    public void onRemoveBrand() {
        chooseBrand = null;
        tvChooseBrand.setText("品牌");
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    @Override
    public void onChooseBrand() {
        startActivity(ChooseCarModelActivity.class, new BundleBuilder()
                .putInt("chooseLevel", 1)
                .putInt("eventTag", 200)
                .create());
    }

    @Subscribe
    public void onChooseBrandEvent(ChooseBrandEvent event) {
        if (event != null && event.getBrandInfo() != null) {
            if (event.getEventTag() == 200) {
                if (chooseBrand != null && chooseBrand.getId().equals(event.getBrandInfo().getId())) {
                    return;
                }
                chooseBrand = event.getBrandInfo();
                tvChooseBrand.setText(chooseBrand.getName());
                loadingLayout.setStatus(LoadingLayout.Loading);
                mvpPresenter.getList(1);
            } else if (event.getEventTag() == 300) {
                customAssistantMorePopup.notifyBrandInfo(event.getBrandInfo());
            }
        }
    }

    private void showChooseBrandPopup() {
        if (customChooseBrandPopup == null) {
            customChooseBrandPopup = new CustomChooseBrandPopup(mActivity);
            customChooseBrandPopup.setListener(this);
        }
        customChooseBrandPopup.initBrandModel(chooseBrand);
        new XPopup.Builder(getContext())
                .atView(llChoosePanel)
                .asCustom(customChooseBrandPopup)
                .show();
    }

    @Override
    public void onChoosePrice(PriceConditionInfo info) {
        choosePrice = info;
        tvChoosePrice.setText(info.getName());
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    private void showChoosePricePopup() {
        if (customChoosePricePopup == null) {
            customChoosePricePopup = new CustomChoosePricePopup(mActivity);
            customChoosePricePopup.setListener(this);
        }
        customChoosePricePopup.initPriceModel(choosePrice);
        new XPopup.Builder(getContext())
                .atView(llChoosePanel)
                .asCustom(customChoosePricePopup)
                .show();
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    @Override
    protected CarGarageAssistantPresenter createPresenter() {
        return new CarGarageAssistantPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<CarInfo>> successResult) {
        page = successResult.getData();
        mHasLoadedOnce = true;
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            mHasLoadedOnce = true;
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onGetCraGradeListSuccess(BaseModel<List<DictInfo>> successResult) {
        gradeList = successResult.getData();
    }

    @Override
    public void onGetCraGradeListFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public void onGetCountryTypeListSuccess(BaseModel<List<DictInfo>> successResult) {
        countryList = successResult.getData();
    }

    @Override
    public void onGetCountryTypeListFailure(BaseModel<Object> failureResult) {

    }

    @Override
    public String getCityName() {
        return cityName == null ? "" : cityName;
    }

    @Override
    public String getBrandId() {
        return chooseBrand != null ? chooseBrand.getId() : "";
    }

    @Override
    public String getPriceMin() {
        return choosePrice != null ? choosePrice.getMin() : "";
    }

    @Override
    public String getPriceMax() {
        return choosePrice != null ? choosePrice.getMax() : "";
    }

    @Override
    public String getCarType() {
        return chooseGrade != null ? chooseGrade.getKey() : "";
    }

    @Override
    public String getCarCountry() {
        return chooseCountry != null ? chooseCountry.getKey() : "";
    }

    public void changeCity(String name) {
        cityName = name;
        mHasLoadedOnce = false;
        lazyLoad();
    }

}
